package com.javasm.adminapi.module.system.service.impl;

import com.javasm.adminapi.common.exception.ExceptionEnum;
import com.javasm.adminapi.common.exception.JavasmException;
import com.javasm.adminapi.login.service.LoginService;
import com.javasm.adminapi.module.system.entity.User;
import com.javasm.adminapi.module.system.service.UserApiService;
import com.javasm.adminapi.module.system.service.UserService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @className: UserApiServiceImpl
 * @description:
 * @author: zcx
 * @date: 2025/10/16 15:25
 * @version: 0.1
 * @since: jdk17
 */
@Service("userApiService")
public class UserApiServiceImpl implements UserApiService {
    @Resource
    LoginService loginService;
    @Resource
    UserService userService;
    @Override
    public User updateByUser(User user) {
        User loginUser = loginService.getLoginUser();
        //填入修改字段
        if(user.getNickname()!=null&&user.getNickname()!=""){
            loginUser.setNickname(user.getNickname());
        }
        if(user.getEmail()!=null&&user.getEmail()!=""){
            loginUser.setEmail(user.getEmail());
        }
        if(user.getPhone()!=null&&user.getPhone()!=""){
            loginUser.setPhone(user.getPhone());
        }
        //修改用户信息
        userService.updateById(loginUser);
        return loginUser;
    }
    @Resource
    PasswordEncoder passwordEncoder;

    @Override
    public void updatePwd(String oldPassword, String newPassword) {
        User loginUser = loginService.getLoginUser();
        if(!passwordEncoder.matches(oldPassword,loginUser.getPassword())){
            throw new JavasmException(ExceptionEnum.Old_Password_Error);
        }

        loginUser.setPassword(passwordEncoder.encode(newPassword));
        userService.updateById(loginUser);

    }
}
